from django.shortcuts import get_object_or_404
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django.http.request import QueryDict
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend

from .models import shenzhenwan
from .serializers import SzwSerializer

# Create your views here.

class SzwPagination(PageNumberPagination):
    page_size_query_param = 'pageSize'
    page_query_param = 'pageIndex'

class SzwViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = shenzhenwan.objects.all().order_by('-date')
    serializer_class = SzwSerializer
    pagination_class = SzwPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['date']

    def create(self, request, *args, **kwargs):
        if request.data['total'] == '':
            request.data['total'] = request.data['yuexian'] + request.data['ruqin'] + request.data['juji'] + request.data['paowu']
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data={'data':serializer.data, 'message':'成功', 'code': '0000'}, status=status.HTTP_201_CREATED, headers=headers)
    
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return Response(data={'data':{'total': len(queryset), 'list': serializer.data}, 'message':'成功', 'code': '0000'}, status=status.HTTP_200_OK)

        serializer = self.get_serializer(queryset, many=True)
        return Response(data={'data':{'total': len(queryset), 'list': serializer.data}, 'message':'成功', 'code': '0000'}, status=status.HTTP_200_OK)
    
    @action(methods=['post'], detail=False)
    def delete(self, request,  *args, **kwargs):
        delete_id = request.query_params.get('ids', None)
        if not delete_id:
            return Response(status=status.HTTP_404_NOT_FOUND)
        for i in delete_id.split(','):
            get_object_or_404(shenzhenwan, pk=int(i)).delete()
        return Response(data={'data':{'total':0}, 'message':'成功', 'code': '0000'}, status=status.HTTP_200_OK)
    